package com.juyu.miliao.scheduler.message;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.common.constant.FanoutExchangeKey;
import com.juyu.miliao.common.constant.GiftWallRabbitMqInfo;
import com.juyu.miliao.common.constant.ReceiveGiftSortRedisKey;
import com.juyu.miliao.scheduler.domin.GiftSpend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 收到礼物排行榜
 * @author xuanqicheng
 * @create 2019-28-11:41
 */
@Component
@Slf4j
public class ReceiveGiftSortMessage {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(GiftWallRabbitMqInfo.RECEIVE_GIFT_SORT_QUEUE),
            exchange = @Exchange(value = FanoutExchangeKey.SEND_GIFT_FANOUT_EXCHANGE_KEY,
                    type = ExchangeTypes.FANOUT)))
    public void getGiftWallMessage(String message){
        if(!StringUtils.isEmpty(message)){
            try {

                GiftSpend giftSpend = JSONObject.parseObject(message, GiftSpend.class);

                String inUserId = Long.toString(giftSpend.getInUserId());

                String key = ReceiveGiftSortRedisKey.EXIST_SEND_ID_BY_INCOME_USER_ID_KEY.getValue(inUserId);

                boolean bl = stringRedisTemplate.opsForSet().isMember(key, giftSpend.getSpendId()+"");

                if(!bl){

                    String zSetKey = ReceiveGiftSortRedisKey.ZSET_RECEIVE_GIFT_SORT_BY_INCOME_USER_ID_KEY.getValue(inUserId);

                    String outUserId = Long.toString(giftSpend.getOutUserId());

                    stringRedisTemplate.opsForZSet().incrementScore(zSetKey,outUserId,giftSpend.getSpend());

                    String sendGiftBySendOutUserAndIncomUserKey = ReceiveGiftSortRedisKey
                            .ZSET_SEND_GIFT_BY_SEND_OUT_USER_AND_INCOME_USER_KEY.getValue(outUserId,inUserId);

                    stringRedisTemplate.opsForZSet().incrementScore(sendGiftBySendOutUserAndIncomUserKey,
                            giftSpend.getGiftId()+"",giftSpend.getNum());

                    stringRedisTemplate.opsForSet().add(key,giftSpend.getSpendId()+"");

                }
            }catch (Exception ex){
                log.error("处理收礼物原始数据错误："+ex.getMessage());
            }
        }
    }

}
